#include <SDL2/SDL.h>
#include <stdio.h>
#include <math.h>

#define ERR(msg) do { \
        fprintf(stderr, "%s at %d in %s\n", msg, __LINE__, __FILE__); \
        exit(1); \
    } while (0)

int main(int argc, char **argv)
{
    /* Init */
    if (SDL_Init(SDL_INIT_VIDEO) < 0) ERR(SDL_GetError());

    SDL_Window *win = SDL_CreateWindow("demo1",
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
        640, 480, SDL_WINDOW_SHOWN);
    if (!win) ERR(SDL_GetError());

    SDL_Renderer *renderer = SDL_CreateRenderer(win, -1,
        SDL_RENDERER_ACCELERATED);
    if (!renderer) ERR(SDL_GetError());

    SDL_Surface *buffer = SDL_LoadBMP("img.bmp");
    if (!buffer) ERR(SDL_GetError());

    SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, buffer); 
    if (!texture) ERR(SDL_GetError());

    SDL_FreeSurface(buffer);

    /* Processing event */
    int running = 1;
    int mx = -1, my = -1;
    double rotate = 0; 
    SDL_Event event;
    SDL_Rect dest;
    while (running) {
        while (SDL_PollEvent(&event) != 0) {
            switch (event.type) {
            case SDL_QUIT: 
                running = 0; 
                break;
            case SDL_MOUSEMOTION:
                mx = event.motion.x; 
                my = event.motion.y; 
                break;
            }
            if (!running) break;

            /* Clear window */
            SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
            SDL_RenderClear(renderer);

            /* Drawing */
            const unsigned char *keys = SDL_GetKeyboardState(NULL);
            if (mx != -1) {
                float w_percent = mx / 640.0f;
                float h_percent = my / 480.0f;
                unsigned char r = round(w_percent * 255);
                unsigned char g = round(h_percent * 255);
                SDL_SetTextureColorMod(texture, r, g, 0);

                mx -= 320;
                my -= 240;
                rotate = atan((float) my / (float) mx) * (180.0f / 3.14f);
                if (mx < 0) rotate -= 180;
            }
            mx = my = -1;

            dest.x = 240; dest.y = 180;
            dest.w = 160; dest.h = 120;
            SDL_RenderCopyEx(renderer, texture, NULL, &dest, rotate, NULL,
                keys[SDL_SCANCODE_F] ? SDL_FLIP_VERTICAL : SDL_FLIP_NONE);

            /* Update window */
            SDL_RenderPresent(renderer);
        }
    }

    /* Free resource */
    SDL_DestroyTexture(texture);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(win);
    SDL_Quit();

    exit(0);
}
